<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <img src="@/assets/logo.svg" alt="万川汇智" class="logo" />
        <h1>万川汇智</h1>
        <p class="subtitle">AI Nexus</p>
      </div>
      
      <form @submit.prevent="handleLogin" class="login-form">
        <div class="form-item">
          <label>账号</label>
          <input 
            v-model="username" 
            type="text" 
            required 
            placeholder="请输入账号"
            autocomplete="username"
          />
        </div>
        
        <div class="form-item">
          <label>密码</label>
          <input 
            v-model="password" 
            type="password" 
            required 
            placeholder="请输入密码"
            autocomplete="current-password"
          />
        </div>

        
        <button type="submit" :disabled="isLoading">
          {{ isLoading ? '登录中...' : '登录' }}
        </button>

        <div class="register-link">
          还没有账号？<a href="#" @click.prevent="showRegisterDialog = true">立即注册</a>
        </div>
      </form>
    </div>

    <!-- 注册对话框 -->
    <el-dialog
      v-model="showRegisterDialog"
      title="注册账号"
      width="460px"
      :close-on-click-modal="false"
      center
      class="register-dialog"
    >
      <el-form
        ref="registerForm"
        :model="registerData"
        :rules="registerRules"
        label-width="100px"
        @submit.prevent="handleRegister"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="registerData.username" 
            placeholder="请输入用户名"
            :input-style="{ padding: '0.75rem' }"
          />
        </el-form-item>
        
        <el-form-item label="昵称" prop="nickname">
          <el-input 
            v-model="registerData.nickname" 
            placeholder="请输入昵称"
            :input-style="{ padding: '0.75rem' }"
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerData.password"
            type="password"
            placeholder="请输入密码"
            show-password
            :input-style="{ padding: '0.75rem' }"
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerData.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
            :input-style="{ padding: '0.75rem' }"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button 
            @click="showRegisterDialog = false"
            class="cancel-btn"
          >
            取消
          </el-button>
          <el-button 
            type="primary" 
            @click="handleRegister" 
            :loading="registerLoading"
            class="register-btn"
          >
            注册
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/userStore'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
const username = ref('')
const password = ref('')
const error = ref('')
const isLoading = ref(false)

// 注册相关
const showRegisterDialog = ref(false)
const registerLoading = ref(false)
const registerForm = ref<FormInstance>()

const registerData = reactive({
  username: '',
  nickname: '',
  password: '',
  confirmPassword: ''
})

const validatePass = (_: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (registerData.confirmPassword !== '') {
      registerForm.value?.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (_: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerData.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePass, trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ]
}

const handleRegister = async () => {
  if (!registerForm.value) return
  
  await registerForm.value.validate(async (valid) => {
    if (valid) {
      registerLoading.value = true
      try {
        const response = await request.post('/auth/register', {
          username: registerData.username,
          password: registerData.password,
          nickname: registerData.nickname
        })
        if (response.data.code === 0 ) {
          ElMessage.success('注册成功，请登录')
          showRegisterDialog.value = false
          // 清空表单
          registerForm.value?.resetFields()
        }
      } catch (err: any) {
        ElMessage.error(err.response?.data?.message || '注册失败')
      } finally {
        registerLoading.value = false
      }
    }
  })
}

const handleLogin = async () => {
  error.value = ''
  isLoading.value = true
  
  try {
    const response = await request.post('/auth/login', {
      username: username.value,
      password: password.value
    })

    const { status, data } = response.data
    
    if (status === 'success' && data) {
      userStore.login({
        username: data.username,
        role: data.role,
        avatar: data.avatar || '',
        token: data.token
      })
      router.push('/')
    }
  } catch (err: any) {
    error.value = err.response?.data?.message || '登录失败'
    ElMessage.error(error.value)
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  height: 100vh; /* 固定高度 */
  display: flex;
  align-items: center;
  justify-content: center;
  background: white; /* 改为白色背景 */
  padding: 1rem;
  overflow: hidden; /* 防止滚动 */
  position: fixed; /* 固定位置 */
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.login-card {
  background: white;
  padding: 2.5rem;
  border-radius: 1rem;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  width: 100%;
  max-width: 400px;
}

.login-header {
  text-align: center;
  margin-bottom: 2rem;
}

.logo {
  width: 4rem;
  height: 4rem;
  margin-bottom: 1rem;
}

h1 {
  font-size: 1.5rem;
  color: #1f2937;
  margin: 0;
}

.subtitle {
  color: #6b7280;
  margin-top: 0.25rem;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

label {
  font-size: 0.875rem;
  color: #4b5563;
  font-weight: 500;
}

input {
  padding: 0.75rem;
  border: 1px solid #e5e7eb;
  border-radius: 0.5rem;
  font-size: 0.95rem;
  transition: all 0.2s;
}

input:focus {
  outline: none;
  border-color: #2563eb;
  box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
}

button {
  background: #2563eb;
  color: white;
  padding: 0.875rem;
  border: none;
  border-radius: 0.5rem;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

button:hover:not(:disabled) {
  background: #1d4ed8;
}

button:disabled {
  background: #93c5fd;
  cursor: not-allowed;
}

.register-link {
  text-align: center;
  font-size: 0.875rem;
  color: #6b7280;
}

.register-link a {
  color: #2563eb;
  text-decoration: none;
}

.register-link a:hover {
  text-decoration: underline;
}

:deep(.el-dialog) {
  border-radius: 0.5rem;
}

.dialog-footer {
  text-align: right;
}

/* 注册弹窗样式 */
:deep(.register-dialog) {
  .el-dialog__header {
    margin: 0;
    padding: 20px 20px 10px;
    text-align: center;
    font-size: 1.25rem;
    color: #1f2937;
  }

  .el-dialog__body {
    padding: 30px 40px;
  }

  .el-form-item__label {
    font-size: 0.875rem;
    color: #4b5563;
    font-weight: 500;
  }

  .el-input__wrapper {
    border-radius: 0.5rem;
    box-shadow: 0 0 0 1px #e5e7eb;
  }

  .el-input__wrapper:hover {
    box-shadow: 0 0 0 1px #2563eb;
  }

  .el-input__wrapper.is-focus {
    box-shadow: 0 0 0 1px #2563eb, 0 0 0 3px rgba(37, 99, 235, 0.1);
  }

  .dialog-footer {
    padding: 10px 0 0;
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  }

  .cancel-btn {
    padding: 0.75rem 1.5rem;
    border-radius: 0.5rem;
    font-size: 0.875rem;
  }

  .register-btn {
    padding: 0.75rem 1.5rem;
    border-radius: 0.5rem;
    font-size: 0.875rem;
    background: #2563eb;
    border-color: #2563eb;
  }

  .register-btn:hover:not(:disabled) {
    background: #1d4ed8;
    border-color: #1d4ed8;
  }

  .register-btn:disabled {
    background: #93c5fd;
    border-color: #93c5fd;
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .login-container {
    padding: 1rem;
    background: white;
  }

  .login-card {
    padding: 1.5rem;
    box-shadow: none;
  }

  .logo {
    width: 3rem;
    height: 3rem;
  }

  h1 {
    font-size: 1.25rem;
  }

  .subtitle {
    font-size: 0.875rem;
  }

  .form-item input {
    padding: 0.625rem;
  }

  button {
    padding: 0.75rem;
  }

  :deep(.register-dialog) {
    .el-dialog__body {
      padding: 20px;
    }

    .el-form-item {
      margin-bottom: 16px;
    }
  }
}
</style> 